import {ChangeEventHandler, FC, useState} from "react";
import DGDialogLayout from "../../../components/DGDialogLayout/DGDialogLayout.tsx";
import DGDrawerLayout from "../../../components/DGDrawerLayout/DGDrawerLayout.tsx";
import {Box, TextField} from "@mui/material";
import {useNavigate} from "react-router-dom";
import DGTextView from "../../../components/DGTextView.tsx";
import AppProvider from "../../../sources/AppProvider.ts";
import DGConnect from "../../../sources/DGConnect.ts";
import {Util} from "../../../sources/Util.ts";

interface DGRegEmailProps {
    state: boolean,
    switchView: (text: string) => void,
}

const DGRegEmail: FC<DGRegEmailProps> = ({state, switchView}) => {
    // 程序全局上下文
    const App = AppProvider.useAppContext();
    // 路由跳转
    const router = useNavigate();
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 邮箱信息
    const [email, setEmail] = useState("");
    // 邮箱错误信息
    const [error, setError] = useState({state: false, text: ""});

    // 更改邮箱信息
    const handleChangeEmail: ChangeEventHandler<HTMLInputElement> = e => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 设置账号信息
        setEmail(e.target.value);
        // 验证邮箱输入是否存在空格
        if (e.target.value.indexOf(' ') > -1) return setError({state: true, text: "不允许存在空格"});
        // 验证邮箱输入的格式是否正确
        if (e.target.value !== "" && !App!.Regex['email'].test(e.target.value)) return setError({
            state: true, text: "邮箱格式输入不正确，请确保邮箱完全输入！"
        });
    }

    // 关闭函数
    const handleClose = () => {
        // 关闭面板
        switchView("")
        // 后退
        router(-1);
    }

    // 提交函数
    const handleSubmit = () => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 验证邮箱输入是否为空
        if (email === "") return setError({state: true, text: "请输入邮箱！"});
        // 验证邮箱输入是否存在空格
        if (email.indexOf(' ') > -1) return setError({state: true, text: "不允许存在空格"});
        // 验证邮箱输入的格式是否正确
        if (email !== "" && !App!.Regex['email'].test(email)) return setError({
            state: true, text: "邮箱格式输入不正确，请确保邮箱完全输入！"
        });
        // 开始加载
        setLoading(true);
        // 发送设置邮箱请求
        DGConnect.POST(JSON.stringify({type: "register", email: email}), result => {
            // 关闭加载
            setLoading(false);
            // 设置错误信息
            if (result["data"]["code"] !== 200) return setError({
                state: true, text: result["data"]["message"] + "错误码：" + result["data"]["code"]
            });
            // 增加邮箱信息
            Util.Storage.setSession("REGISTER-EMAIL", email);
            // 成功跳转
            switchView("reg_code");
        }, error => {
            // 关闭加载
            setLoading(false);
            // 设置错误信息
            setError({state: true, text: "遇到了一些问题，请尝试重试，或者及时联系我们！错误信息：" + error["stack"]});
        });
    }

    // DOM 节点
    const ContentView = (<>
        <DGTextView Body Bold>
            尊敬的用户，为了确保您的账户有效性，注册账户时需要绑定并验证您的邮箱。感谢您的理解与支持。
            请输入一个没有绑定逐梦园账户的邮箱：
        </DGTextView>
        {/* 邮箱输入框 */}
        <TextField
            type="email" label="请输入邮箱" disabled={loading} margin="dense" variant="standard"
            value={email} autoComplete="email" onChange={handleChangeEmail}
            error={error.state} helperText={error.text} autoFocus fullWidth required/>
    </>);

    // 返回组件节点
    return (<Box>
        {/* DGDialogLayout 样式 */}
        <DGDialogLayout
            submit={{name: "继续", click: () => handleSubmit()}}
            back={{name: "返回", click: () => switchView("login_index")}}
            title="绑定邮箱" state={state} close={() => handleClose()} load={loading} PANEL>
            {ContentView}
        </DGDialogLayout>
        {/*DGDrawerLayout 样式 */}
        <DGDrawerLayout
            submit={{name: "继续", click: () => handleSubmit()}}
            more={{name: "返回", click: () => switchView("login_index")}}
            title="绑定邮箱" state={state} close={() => handleClose()} flex="bottom" load={loading} PANEL>
            {ContentView}
        </DGDrawerLayout>
    </Box>);
}
export default DGRegEmail;